// Package grpc
// Created by GoLand
// @User: lenora
// @Date: 2024/8/27
// @Time: 14:22

package grpc

import (
	"camp/microbook/api/proto/gen/interactive"
	"camp/microbook/interactive/domain"
	"camp/microbook/interactive/service"
	"context"
	"google.golang.org/grpc"
)

type InteractiveServer struct {
	intrv1.UnimplementedInteractiveServiceServer
	svc service.InteractiveService
}

func NewInteractiveServer(svc service.InteractiveService) *InteractiveServer {
	return &InteractiveServer{svc: svc}
}

func (srv *InteractiveServer) Register(server *grpc.Server) {
	intrv1.RegisterInteractiveServiceServer(server, srv)
}

func (srv *InteractiveServer) IncrReadCnt(ctx context.Context, req *intrv1.IncrReadCntReq) (*intrv1.Response, error) {
	err := srv.svc.IncrReadCnt(ctx, req.GetBiz(), req.GetBizId())
	return new(intrv1.Response), err
}

func (srv *InteractiveServer) IncrLikeCnt(ctx context.Context, req *intrv1.LikeCntReq) (*intrv1.Response, error) {
	err := srv.svc.IncrLikeCnt(ctx, req.GetBiz(), req.GetId(), req.GetUserId())
	return new(intrv1.Response), err
}

func (srv *InteractiveServer) DecrLikeCnt(ctx context.Context, req *intrv1.LikeCntReq) (*intrv1.Response, error) {
	err := srv.svc.DecrLikeCnt(ctx, req.GetBiz(), req.GetId(), req.GetUserId())
	return new(intrv1.Response), err
}

func (srv *InteractiveServer) Collect(ctx context.Context, req *intrv1.CollectReq) (*intrv1.Response, error) {
	err := srv.svc.Collect(ctx, req.GetBiz(), req.GetId(), req.GetCid(), req.GetUserId())
	return new(intrv1.Response), err
}

func (srv *InteractiveServer) Get(ctx context.Context, req *intrv1.GetReq) (*intrv1.GetResp, error) {
	res, err := srv.svc.Get(ctx, req.GetBiz(), req.GetId(), req.GetUserId())
	return &intrv1.GetResp{Interactive: srv.toDTO(res)}, err
}

func (srv *InteractiveServer) GetByIds(ctx context.Context, req *intrv1.GetByIdsReq) (*intrv1.GetByIdsResp, error) {
	res, err := srv.svc.GetByIds(ctx, req.GetBiz(), req.GetIds())
	if err != nil {
		return nil, err
	}
	data := make(map[uint64]*intrv1.Interactive, len(res))
	for _, v := range res {
		data[v.BizId] = srv.toDTO(v)
	}
	return &intrv1.GetByIdsResp{Res: data}, err
}

// d(data)t(transport)o(object)
func (srv *InteractiveServer) toDTO(interactive domain.Interactive) *intrv1.Interactive {
	return &intrv1.Interactive{
		BizId:      interactive.BizId,
		ReadCnt:    interactive.ReadCnt,
		LikeCnt:    interactive.LikeCnt,
		Liked:      interactive.Liked,
		CollectCnt: interactive.CollectCnt,
		Collected:  interactive.Collected,
	}
}
